/**
 * 远光ECP平台3.0版本 http://www.ygsoft.com/ Grace [Gris Application Cloud-Computing
 * Extension]
 * Copyright(c) 1998 - 2020 YGSoft.Inc, All Rights Reserved
 * 
 * ecp.component.attatchView.js
 * 
 * 下载预览附件
 * 
 * 
 * 变更版本：
 * Created by zhengxianwei@ygsoft.com 2016-09-13
 */
define(["jquery","ecp.utils", "ecp.service","ecp.utils.i18n"],function($, utils, $ecpService,i18n){
	/**
	 * 默认参数.
	 */
	var defaultOption = {
			data : [],
			loginContext:{}
	};
	/**
	 * 附件列表模式.
	 */
	var ATTACH_LIST_MODE_HEADER = '<thead><tr>'
		+ '<td style="width: 60%;">'+i18n.upload.fileName+'</td>'
		+ '<td style="width: 10%;">'+i18n.upload.type+'</td>'
		+ '<td style="width: 10%;">'+i18n.upload.size+'</td>'
		+ '<td style="width: 10%; text-align: center;">'+i18n.upload.privew+'</td>'
		+ '<td style="width: 10%; text-align: center;">'+i18n.upload.download+'</td>'
		+ '</tr><thead>';
	
	var ATTACH_LIST_MODE_ROW = '<tr attachgid="{{attachgid}}">'
        +'<td><i class="fa fa-file-text"></i> {{fileName}} </td>'
        +'<td>{{fileType}}</td>'
        +'<td><span>{{fileLength}}</span></td>'
        +'<td style="text-align: center;">{{isPerviewable}}</td>'
        +'<td style="text-align: center;"><a class="download-link" data-index="{{index}}" tabindex=-1><i class="fa fa-download"></i></a></td>'
        +'</tr>';
	
	
	function isPerviewable(filetype) {
    	return /(JPG|JPEG|BMP|GIF|PNG|PDF|TXT)/i.test(filetype);
    }
	
	function isOfficeFile(filetype) {
		return /(PPT|PPTX|XLS|XLSX|DOC|DOCX)/i.test(filetype);
	}
	function isImg(filetype) {
    	return /(JPG|BMP|GIF|TIF|PNG|JPEG)/i.test(filetype);
    }
	function getServer() {
		var loc = window.location;
		return loc.protocol + "//" + loc.host;
	}
	var IMG_MIN_HEIGHT = 280;
    var IMG_MIN_WIDTH = 400;
    
    var IMG_SCREEN_HEIGHT = 545;
    var IMG_SCREEN_WIDTH = 895;
    
    var IMG_SCREEN_SIZE = IMG_SCREEN_HEIGHT*IMG_SCREEN_WIDTH;
	
	var ATTACH_ITEM_TEMPLATE = '<div class="item fill-height" style="display:none">'
		+'<iframe id="{{file.gid}}" src="" class="attach-view-iframe" frameborder="0" style="width:100%;height:400px;"></iframe>'
		+'</div>';
	//图片参数map
    var imgParamMap = {};
    var abort = false;
	var xhr;
	
	/**
	 * 声明EcpUploader对象.
	 */
	var Attachment = function(container,options,noRender){
		if(!container || container.length === 0){return;}
		this.init(container,options);
	}
	
	/**
	 * 通过原型定义相关方法，比如渲染、赋值等等.
	 */
	Attachment.prototype = {
	    /**
	     * 初始化.
	     * @param {Object} container 占位符
		 * @param {Object} option 控件渲染配置属性
	     */
		init: function(container,option){
			this.attachContainer = container;
			this.serialNo = new Date().getTime();
			this.option = $.extend(true, {}, defaultOption, option);
			this.dataSource = this.option.data;
		},
		
		/**
		 * 渲染面板.
		 */
		renderPanel: function(){
			var containerDiv = $('<div id="billAttachmentInfo" class="bill-info-item-div  mobile-ywdj-detail-attachment-info"><div>');
			this.attachContainer.append(containerDiv);
			var listModeDiv = $('<div class="attachment-list-mode"></div>');
			this.attachContainer.append(listModeDiv);
			// 添加表头信息
			var listModeTable = $('<table class="mobile-attachment-table table table-hover table-striped table-bordered" cellpadding="0" cellspacing="0" border="0" style="width:100% !important;margin-bottom:0;"></table>');
			listModeDiv.append(listModeTable);
			listModeTable.append(ATTACH_LIST_MODE_HEADER);
			var $tbody = $("<tbody></tbody>");
			listModeTable.append($tbody);
			var map = {};
			var attachList = this.dataSource;
			$.each(attachList, function(i, doc) {
				map[doc.gid] = doc;
			});
			var electronicdoc = [];
			$.each(map, function(doc) {
				electronicdoc.push(doc);
			});
			var item, i, j = attachList.length;
			var fileId, file, fileLength, fileType, fileName;
			var bodyContent = [];
			for (i = 0; i < j; i++) {
				fileId = electronicdoc[i];
				file = map[fileId];
				fileLength = file.fileLength.replace(/,/g,"");
				fileType = file.fileType;
				fileName = file.fileAllName;
				if (!fileType) {
					fileType = "";
				}
				if (isNaN(fileLength)) {
					fileLength = "未知";
				}

				var rowHtml = ATTACH_LIST_MODE_ROW.replace("{{fileName}}", file.fileName).replace(
						"{{attachgid}}", fileId);
				if (fileType) {
					fileType = fileType.toUpperCase();
					rowHtml = rowHtml.replace("{{fileType}}", fileType);
				} else {
					rowHtml = rowHtml.replace("{{fileType}}", "&nbsp;");
					}
				rowHtml = rowHtml.replace("{{fileLength}}",fileLength + "KB");
				fileType = fileType.toUpperCase();
				if (isPerviewable(fileType) || isOfficeFile(fileType)) {
					rowHtml = rowHtml.replace("{{isPerviewable}}",' <a class="attach-preview-link" tabindex=-1 data-index={{index}}><i class="fa fa-eye"></i></a>');
				}  else {
					rowHtml = rowHtml.replace("{{isPerviewable}}",'&nbsp;');
				}
				rowHtml = rowHtml.replace(new RegExp("{{index}}", 'g'), i);
				bodyContent.push(rowHtml);
			}
			$tbody.append(bodyContent.join(""));
			this.bindContentEvent(map,electronicdoc);
		},
		
		/**
		 * 预览文件.
		 * @param {Object} file 文件对象
		 * @param {Object} map
		 * @param {Boolean} electronicdoc 文档
		 */
		previewFile: function(file, map, electronicdoc){
			map = map;
			var uuid = file.gid;
			var type = file.fileType;
			var url = this.getAttachmentPreviewURL(file);
			if (isOfficeFile(type)) {
				var isNodeWebkit = utils.isNodeWebkitBrower()();
				var isChrome = utils.isChromeBrower();
				if (isNodeWebkit || isChrome) {
					var obj = me.getNpapiObj();
					obj.runExe("iexplore.exe\0", url+ "\0");
				} else {
					window.open(url);
				}
			} else {
				this.attachContainer.attr("preview", true);
				var ext = "";
				if (file.fileType) {
					ext = file.fileType.toUpperCase();
				}
				if (ext === "PDF") {
					url = "/grm/ecp/webcore/components/upload/pdf.html#" + encodeURIComponent(url);
				} else if (ext === "TXT") {
					url = "/grm/ecp/webcore/components/upload/txt.html#" + encodeURIComponent(url);
				}
				this.viewAttachment(uuid,url,map,electronicdoc);
			}
		},
		
		/**
		 * 预览附件.
		 * @param {String} uuid 随机
		 * @param {Object} map
		 * @param {Boolean} electronicdoc 文档
		 */
		viewAttachment: function(uuid,url,map,electronicdoc) {
			var me = this;
			$.ajax({
				url : "/grm/ecp/webcore/components/upload/viewattach.html",
				type : "GET",
				success : function(res, textStatus, jqXHR) {
					if (res) {
						$('body').append(res.replace(/@serialid/ig,me.serialNo));
						var dlg = me.getJqElement("attachViewDlg");
						me.renderViewArea(uuid,url,map,electronicdoc);
						me.bindAttachEvent(uuid,url,map,electronicdoc);
						dlg.modal();
					}
				}
			});
		},
		
		/**
		 * 构造预览区域.
		 */
		renderViewArea: function(uuid,url,map,electronicdoc) {
			var me = this;
			var container = me.getJqElement("viewArea");
			var i,file,j = electronicdoc.length, buf=[];
			for (i = 0; i < j; i++) {
				file = map[electronicdoc[i]];
				if (isPerviewable(file.fileType)) {
					buf.push(ATTACH_ITEM_TEMPLATE.replace("{{file.gid}}", file.gid));
				}
			}
			container.append(buf.join(""));
			var iframe = container.find("#" + uuid);
			iframe.attr("src",url);
			var dlg = me.getJqElement("attachViewDlg");
			dlg.find(".modal-title").children("span").text(map[uuid].fileName + "." + map[uuid].fileType);
			if (isImg(map[uuid].fileType)) {
				me.toggleImgButtom(true);
				iframe.load(function(){
					me.parseImgCache(iframe, map[uuid]);
				});
			} else {
				me.toggleImgButtom(false);
			}
			iframe.parent().addClass("active").show();
		},
		
		parseImgCache: function(iframe, file) {
			if (!iframe || !file) return;
			var gid = file.gid;
			var frameBody = $(iframe[0].contentWindow.document).find('body');
			var curImgObj = frameBody.find("img");
			curImgObj.attr("uuid", gid);
			if(!imgParamMap[gid]) {
				var height = curImgObj.height();
        		var width = curImgObj.width();
    			imgParamMap[gid] = {
    				height:	height,
    				width:width,
    				rotation:0
    			};
    		}
		},
		
		/**
         * 显示或者隐藏图片按钮
         */
		toggleImgButtom: function(isShow) {
        	if (isShow) {
        		this.getJqElement("imgOriginaSizeBtn").css("visibility","visible");
        		this.getJqElement("imgScreenSetBtn").css("visibility","visible");
        		this.getJqElement("zoomInBtn").css("visibility","visible");
        		this.getJqElement("zoomOutBtn").css("visibility","visible");
        		this.getJqElement("rotationLeftBtn").css("visibility","visible");
        		this.getJqElement("rotationRightBtn").css("visibility","visible");
        	} else {
        		this.getJqElement("imgOriginaSizeBtn").css("visibility","hidden");
        		this.getJqElement("imgScreenSetBtn").css("visibility","hidden");
        		this.getJqElement("zoomInBtn").css("visibility","hidden");
        		this.getJqElement("zoomOutBtn").css("visibility","hidden");
        		this.getJqElement("rotationLeftBtn").css("visibility","hidden");
        		this.getJqElement("rotationRightBtn").css("visibility","hidden");
        	}
        },
		
		/**
		 * 绑定附件事件.
		 */
        bindAttachEvent: function(uuid,url,map,electronicdoc){
        	var me = this;
			var dlg = this.getJqElement("attachViewDlg");
			dlg.on('hidden.bs.modal', function() {
				me.attachContainer.removeAttr("preview");
                dlg.remove();
            });
			//上一张
			dlg.on("click","[data-direction='prev']", function(){
				if (electronicdoc.length ===1) return;
				var contain = me.getJqElement("viewArea"),
					active = contain.find(".active"),
					prev = active.prev();
				if (prev.length === 0) {
					prev = active.siblings().last();
				}
				var fileId = prev.find("iframe").attr("id"),
					file= map[fileId];
				if(!file){return;}
				active.css("display","none").removeClass("active");
				prev.css("display","block");
				prev.addClass("active");
				
				if (isImg(file.fileType)) {
					me.toggleImgButtom(true);
				} else {
					me.toggleImgButtom(false);
				}
				var url = me.getAttachmentPreviewURL(file);
				var iframe = prev.find("iframe");
				if (!iframe.attr("src")) {
					var ext = "";
					if (file.fileType) {
						ext = file.fileType.toUpperCase();
					}
					if (ext === "PDF") {
						url = "/grm/ecp/webcore/components/upload/pdf.html#" + encodeURIComponent(url);
					} else if (ext === "TXT") {
						url = "/grm/ecp/webcore/components/upload/txt.html#" + encodeURIComponent(url);
					}
					iframe.attr("src", url);
					iframe.load(function(){
						me.parseImgCache(iframe, file);
					});
				}
				dlg.find(".modal-title").children("span").text(file.fileName + "." + file.fileType);
			});
			//下一张
			dlg.on("click","[data-direction='next']", function() {
				if (electronicdoc.length ===1) return;
				var contain = me.getJqElement("viewArea"),
					active = contain.find(".active"),
					next = active.next();
				if (next.length === 0) {
					next = active.siblings().first();
				}
				var fileId = next.find("iframe").attr("id"),
					file= map[fileId];
				if(!file){return;}
				active.css("display","none").removeClass("active");
				next.css("display","block");
				next.addClass("active");
				if (isImg(file.fileType)) {
					me.toggleImgButtom(true);
				} else {
					me.toggleImgButtom(false);
				}
				var url = me.getAttachmentPreviewURL(file);
				var iframe = next.find("iframe");
				if (!iframe.attr("src")) {
					var ext = "";
					if (file.fileType) {
						ext = file.fileType.toUpperCase();
					}
					if (ext === "PDF") {
						url = "/grm/ecp/webcore/components/upload/pdf.html#" + encodeURIComponent(url);
					} else if (ext === "TXT") {
						url = "/grm/ecp/webcore/components/upload/txt.html#" + encodeURIComponent(url);
					}
					iframe.attr("src", url);
					iframe.load(function(){
						me.parseImgCache(iframe, file);
					});
				}
				dlg.find(".modal-title").children("span").text(file.fileName + "." + file.fileType);
			});
			
			//下载
			me.getJqElement("downloadFileBtn").on("click", function(){
				var contain = me.getJqElement("viewArea");
				var active = contain.find(".active");
				var fileId = active.find("iframe").attr("id");
				var file= map[fileId];
				me.fileDownload(file);
			});
			
			//实际大小
			me.getJqElement("imgOriginaSizeBtn").on("click", function(event) {
        		me.changeImgToOriginalSize(event);
        	});
        	
        	//屏幕自适应
			me.getJqElement("imgScreenSetBtn").on("click", function(event) {
        		me.imgScreenSet(event);
        	});
        	
        	//放大
			me.getJqElement("zoomInBtn").on("click", function(event) {
        		me.zoomIn(event);
        	});
        	
        	//缩小
			me.getJqElement("zoomOutBtn").on("click", function(event) {
        		me.zoomOut(event);
        	});
        	
        	//顺时针旋转
			me.getJqElement("rotationRightBtn").on("click", function(event) {
        		me.rotationRight(event);
        	});
        	
        	//逆时针旋转
			me.getJqElement("rotationLeftBtn").on("click", function(event) {
        		me.rotationLeft(event);
        	});
		},
		/**
         * 图片实际大小
         */
		changeImgToOriginalSize: function(event) {
			var contain = this.getJqElement("viewArea");
        	var toLoad = contain.find(".active").find("iframe");
            if (!toLoad || toLoad.length === 0) {
            	return;
            }
            var uuid = toLoad.attr("id");
            var $body = $(toLoad[0].contentWindow.document).find('body');
        	var curImgObj = $body.find("img[uuid='"+uuid+"']");
        	if (!curImgObj || curImgObj.length === 0) {
        		return;
        	}
        	var param = imgParamMap[uuid];
        	if (!param) {
        		return;
        	}
        	var imgHeight = param.height;
        	var imgWidth = param.width;
        	curImgObj.height(imgHeight);
    		curImgObj.width(imgWidth);
        	if (event) {
        		event.preventDefault();
            	event.stopPropagation();
        	}
        },
        
		/**
         * 屏幕自适应
         */
		imgScreenSet: function(event) {
        	var contain = this.getJqElement("viewArea");
        	var toLoad = contain.find(".active").find("iframe");
            if (!toLoad || toLoad.length === 0) {
            	return;
            }
            var uuid = toLoad.attr("id");
            var $body = $(toLoad[0].contentWindow.document).find('body');
        	var curImgObj = $body.find("img[uuid='"+uuid+"']");
        	if (!curImgObj || curImgObj.length === 0) {
        		return;
        	}
        	//图片参数
        	var param = imgParamMap[uuid];
        	if (!param) {
        		return;
        	}
        	var imgHeight = param.height;
        	var imgWidth = param.width;
        	var newHeight;
        	var newWidth;
        	if (imgWidth > IMG_SCREEN_WIDTH) {
    			//按宽度缩放
    			newWidth = IMG_SCREEN_WIDTH;
    			newHeight = newWidth*imgHeight/imgWidth;
    			if (newHeight > IMG_SCREEN_HEIGHT) {
    				newHeight = IMG_SCREEN_HEIGHT;
    			}
    		} else if (imgHeight > IMG_SCREEN_HEIGHT){
    			//按高度缩放
    			newHeight = IMG_SCREEN_HEIGHT;
    			newWidth = newHeight*imgWidth/imgHeight;
    			if (newWidth > IMG_SCREEN_WIDTH) {
    				newWidth = IMG_SCREEN_WIDTH;
    			}
    		} else {
    			newHeight = imgHeight;
    			newWidth = imgWidth;
    		}
    		curImgObj.height(newHeight);
			curImgObj.width(newWidth);
			
        	if (event) {
        		event.preventDefault();
            	event.stopPropagation();
        	}
        },
        
        /**
         * 放大图片
         */
        zoomIn: function(event) {
        	
        	var contain = this.getJqElement("viewArea");
        	var toLoad = contain.find(".active").find("iframe");
            if (!toLoad || toLoad.length === 0) {
            	return;
            }
            var uuid = toLoad.attr("id");
            var $body = $(toLoad[0].contentWindow.document).find('body');
        	var curImgObj = $body.find("img[uuid='"+uuid+"']");
        	if (!curImgObj || curImgObj.length === 0) {
        		return;
        	}
        	//图片参数
        	var param = imgParamMap[uuid];
        	if (!param) {
        		return;
        	}
        	var rotation = param.rotation;
        	if (rotation < 0) {
        		rotation = -rotation;
        	}
        	rotation = rotation%4;
        	
        	var imgHeight = param.height;
        	var imgWidth = param.width;
        	
			var maxHeight,maxWidth;
			//原始尺寸小于屏幕的，按照屏幕大小的
			if (imgHeight*imgWidth <= IMG_SCREEN_SIZE) {
				maxHeight = IMG_SCREEN_HEIGHT;
				maxWidth = IMG_SCREEN_WIDTH;
			} else {
				maxHeight = imgHeight;
				maxWidth = imgWidth;
			}
			
			var curHeight = curImgObj.height();
        	var curWidth= curImgObj.width();
			var width = curWidth+30;
			var height = curHeight+30;
			if (width > maxWidth) {
				width = maxWidth;
				height = width*curHeight/curWidth;
			} else if (height > maxHeight){
				height = maxHeight;
				width = height*curWidth/curHeight;
			} else {
				//按宽度放大
				if (rotation == 2 || rotation == 0) {
					height = width*curHeight/curWidth;
				} else {
					//垂直状态按照高度放大
					width = height*curWidth/curHeight;
				}
			}
			curImgObj.height(height);
    		curImgObj.width(width);
    		
        	if (event) {
        		event.preventDefault();
            	event.stopPropagation();
        	}
        },
        
        /**
         * 缩小图片
         */
        zoomOut : function(event) {
        	var contain = this.getJqElement("viewArea");
        	var toLoad = contain.find(".active").find("iframe");
            if (!toLoad || toLoad.length === 0) {
            	return;
            }
            var uuid = toLoad.attr("id");
            var $body = $(toLoad[0].contentWindow.document).find('body');
        	var curImgObj = $body.find("img[uuid='"+uuid+"']");
        	if (!curImgObj || curImgObj.length === 0) {
        		return;
        	}
        	//图片参数
        	var param = imgParamMap[uuid];
        	if (!param) {
        		return;
        	}
        	var rotation = param.rotation;
        	if (rotation < 0) {
        		rotation = -rotation;
        	}
        	rotation = rotation%4;
        	
        	var imgHeight = param.height;
        	var imgWidth = param.width;
        	
        	var curHeight = curImgObj.height();
        	var curWidth= curImgObj.width();
			var width = curWidth-30;
			var height = curHeight-30;
			if (width < IMG_MIN_WIDTH) {
				width = IMG_MIN_WIDTH;
				height = width*curHeight/curWidth;
			} else if (height < IMG_MIN_HEIGHT) {
				height = IMG_MIN_HEIGHT;
				width = height*curWidth/curHeight;
			}  else {
				//按宽度缩小
				if (rotation == 2 || rotation == 0) {
					height = width*curHeight/curWidth;
				} else {
					//垂直状态按照高度放大
					width = height*curWidth/curHeight;
				}
			}
			curImgObj.height(height);
    		curImgObj.width(width);
        	if (event) {
        		event.preventDefault();
            	event.stopPropagation();
        	}
        },
        
        /**
         * 顺时针旋转
         */
        rotationRight: function(event) {
        	var contain = this.getJqElement("viewArea");
        	var toLoad = contain.find(".active").find("iframe");
            if (!toLoad || toLoad.length === 0) {
            	return;
            }
            var uuid = toLoad.attr("id");
            var $body = $(toLoad[0].contentWindow.document).find('body');
        	var curImgObj = $body.find("img[uuid='"+uuid+"']");
        	var curImgObj = $body.find("img[uuid='"+uuid+"']");
        	if (!curImgObj || curImgObj.length === 0) {
        		return;
        	}
        	//参数
        	var param = imgParamMap[uuid];
        	if (!param) {
        		return;
        	}
        	var curRotation = param.rotation;
    		curRotation++;
    		curImgObj.rotate({
                animateTo: curRotation*90
            }); 
    		imgParamMap[uuid].rotation = curRotation;
        	if (event) {
        		event.preventDefault();
            	event.stopPropagation();
        	}
        },
        
        /**
         * 逆时针旋转
         */
        rotationLeft: function(event) {
        	var contain = this.getJqElement("viewArea");
        	var toLoad = contain.find(".active").find("iframe");
            if (!toLoad || toLoad.length === 0) {
            	return;
            }
            var uuid = toLoad.attr("id");
            var $body = $(toLoad[0].contentWindow.document).find('body');
        	var curImgObj = $body.find("img[uuid='"+uuid+"']");
        	if (!curImgObj || curImgObj.length === 0) {
        		return;
        	}
        	//参数
        	var param = imgParamMap[uuid];
        	if (!param) {
        		return;
        	}
        	var curRotation = param.rotation;
    		curRotation--;
    		curImgObj.rotate({
                animateTo: curRotation*90
            }); 
    		imgParamMap[uuid].rotation = curRotation;
            if (event) {
        		event.preventDefault();
            	event.stopPropagation();
        	}
        },
        /**
    	 * 通过ID获取jquery元素.
    	 * @param id 元素ID
    	 */
        getJqElement: function(id) {
    		return $("#" + id + this.serialNo);
    	},
    	
        getNpapiObj: function(id, type) {
			var dllToolObj = null;
			if (window.addEventListener) {
				dllToolObj = document.getElementById("dlltool");
				if (dllToolObj == null) {
					dllToolObj = document.createElement("embed");
					dllToolObj.id = "dlltool";
					dllToolObj.type = "application/rpygtooljs";
					dllToolObj.width = 1;
					dllToolObj.height = 1;
					var ddd = document.getElementsByTagName("BODY");
					ddd[0].appendChild(dllToolObj);
				}
			}
			return dllToolObj;
		},
		downLoad: function(name, url, size) {
			if (isNaN(utils.getIEVersion())) {
				var doc = document;
				dlf = doc.getElementById("fileDownloadFrame");
				if (dlf == null) {
					dlf = doc.createElement("iframe");
					dlf.id = "fileDownloadFrame";
					dlf.style.display="none";
					doc.body.appendChild(dlf);
				}
				dlf.src = url;
			} else {
				window.open(url);
			}
		},
		
		bindBaseEvent: function() {
			dlg.on('hide.bs.modal', function() {
				abort = true;
				xhr.abort();
	        });
		},
		
		downloadFile: function(fileName, url, size) {
			this.downLoad(fileName, url, size);
		},
		bindContentEvent: function(map,electronicdoc) {
			var me = this;
			// 下载
			this.attachContainer.off("click").on("click", "a.download-link", function() {
				var el = $(this);
				var fileId = el.parents("tr").attr("attachgid");
				var file = map[fileId];
				me.fileDownload(file);
			 }).on("click", ".fa-eye",function(e){
				//预览
				var el = $(this);
				var fileId = el.parents("tr").attr("attachgid");
				var file = map[fileId];
				me.previewFile(file,map,electronicdoc);
			 });
		},
		fileDownload: function(file) {
			var fileType = file["fileType"];
			var userId = this.option.loginContext.userId;
			var compId = this.option.loginContext.compId;
			var size = parseInt(file["fileLength"]
					.replace(/,/g)) * 1024;
			var url = this.getAttachmentDownLoadURL(file, userId, compId);
			var fileName = file["fileName"] + '.' + fileType;
			if (fileType) {
				fileType = fileType.toUpperCase();
			}
			// 在封装的客户端调用
			var isNodeWebkit = utils.isNodeWebkitBrower();
			var isChrome = utils.isChromeBrower();
			if ((isNodeWebkit || isChrome) && /(PPT|PPTX|XLS|XLSX|DOC|DOCX)/i.test(fileType)) {
				try {
					var serverAddress = getServer();
					// office用预览地址打开
					var previewUrl = file.previewUrl;
					if (previewUrl) {
						if (previewUrl.indexOf("/") === 0) {
							previewUrl = serverAddress + previewUrl;
						} else {
							previewUrl = serverAddress + "/" + previewUrl;
						}
					}
					var obj = this.getNpapiObj();
					obj.runExe("iexplore.exe\0", previewUrl+ "\0");
				} catch (e) {
					this.downloadFile(fileName, url, size);
				}
				return;
			}
			this.downloadFile(fileName, url, size);
		},
		/**
		 * 获取预览地址.
		 */
		getAttachmentPreviewURL : function(file) {
			if (!file) {
				return "";
			}
			var returnUrl = "";
			var serverAddress = getServer();
			var previewUrl = file.previewUrl;
			if (previewUrl) {
				if (previewUrl.indexOf("/") === 0) {
					returnUrl = serverAddress + previewUrl;
				} else {
					returnUrl = serverAddress + "/" + previewUrl;
				}
			}
			return returnUrl;
		},
		getAttachmentDownLoadURL: function(file, userCode, unitCode) {
			if (!file) {
	     		 return "";
	     	}
	     	var serverAddress = getServer();
	     	var uuid = file.gid;
	     	var fileName = encodeURIComponent(file.fileName);
	     	//测试下载地址
	     	var downloadUrl  = serverAddress + "/grm/gris/contentmanage.ecmDownLoadServlet?fileName=" + fileName + "&fileType="+ file.fileType + "&userCode="+ userCode +"&orgCode=" + unitCode + "&resId="+uuid;
	     	return downloadUrl;
	    }

	};
	(function($) {
		var old = $.fn.acpAttachment;
		$.fn.acpAttachment = function(option){
			var me = this;
			option = option || {};
			var type = typeof(option);
			//如果第一个参数传入的是对象或空则初始化空件，如果传入的是字符串，则认为是调用里面的内部方法。
			if (type === "object") {
				var eus = [];
				this.each(function() {
					var instanceOption = $.extend({}, option, true);
					var instance = new Attachment($(this), instanceOption);
					this.acpAttachment = instance;
					eus.push(instance);
				});
				if(eus.length === 1){
					eus = eus[0];
				}
				return eus;
			} else if (type === "string") {
				var args = Array.prototype.slice.call(arguments, 1);
				if (Attachment.prototype[option]) {
					return Attachment.prototype[option].call(args);
				}
			} else if (option === true) {
				return me[0] && me[0].acpAttachment;
			}
		};
		$.fn.acpAttachment.Constructor = Attachment;
		$.fn.acpAttachment.noConflict = function() {
			$.fn.acpAttachment = old;
			return this;
		};
	}(jQuery));
	return Attachment.prototype;
		
});